<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
namespace Agp\CoreBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\DependencyInjection\Container;
use JMS\DiExtraBundle\Annotation\Validator;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Inject;

/**
 * Description of TerminalDisponivelValidator
 *
 * @author bondcs
 * @Validator("terminal_disponivel")
 */
class TerminalDisponivelValidator extends ConstraintValidator {
    
    protected $container;
    protected $user;

    /**
     * @InjectParams({
     *      "container" = @inject("service_container")
     * })
     * 
     * @param \Symfony\Component\DependencyInjection\Container $containeir
     */
    public function __construct(Container $container) {
        $this->container = $container;
    }

    public function validate($agenda, Constraint $constraint) {
        
        if ($agenda->getDtEnvio() != null AND $agenda->getDtRecebimento() != null){
        $user = $this->container->get('security.context')->getToken()->getUser();
        $totalDisponivel = $this->getConfig()->getQtdeTerminalDisponivel();

        $totalIndisponivel = $this->container->get('agp.agenda.repository')->getTotalIndisponivel($agenda);

        if ($agenda->getCodAgenda() != null){
//            $em = $this->container->get('doctrine')->getEntityManager('default');
//            $previousAgenda = $em->getRepository('AgpCoreBundle:Agenda')->findOneBy(array('codAgenda' => $agenda->getCodAgenda()));
//            $uow = $em->getUnitOfWork();
//            $uow->computeChangeSets();
//            $changeset = $uow->getEntityChangeSet($previousAgenda);
//            $totalDisponivel+= $changeset['qtdeTerminal'][0]; 
//            $totalIndisponivel += $changeset['qtdeTerminal'][0];

        }
        
        //if ($agenda->getCodAgenda() == null){
        
            $totalTerminal = $totalDisponivel - $totalIndisponivel;
            
            if ($agenda->getQtdeTerminal() <= 0){
                   $this->context->addViolation("Utilize pelo menos um terminal.");
            }

            if ($agenda->getQtdeTerminal() > $totalTerminal){
                   $this->context->addViolation($constraint->message, array('%qtde%' => $totalTerminal < 0 ? '0' : $totalTerminal));
            }
        //}
        }
    }
    
    public function getConfig(){
        $em = $this->container->get('doctrine')->getManager();
        $config = $em->find('AgpCoreBundle:ConfiguracaoAgape', 1);
        return $config;
    }
}

?>
